package com.inter.controller.paynotify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.OrderPaymentManager;
import com.inter.entity.common.UserboundPaymentOrder;
import com.inter.entity.payresults.PaypalNotificationpaymentResults;
import com.inter.entity.payresults.PaypalpaymentResults;
import com.inter.entity.payresults.paypal.*;
import com.inter.entity.pojo.Constant;
import com.inter.service.NotificationpaymentService;
import com.inter.service.OrderPaymentManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;

@Controller
public class PaypalpayNotifyController {
    @Autowired
    private OrderPaymentManagerService orderPaymentManagerService;
    @Autowired
    private NotificationpaymentService notificationpaymentService;
    //支付方式：1-公众号支付，2-paypal，3-oceanpay，4-H5微信支付
    private String payType = "2";

    @RequestMapping(value = "/paypalNotifyCallback")
    @CrossOrigin
    public String notifyCallback(HttpServletRequest request, @RequestBody String requestStr) throws Exception {
        try {
            request.setCharacterEncoding("utf-8");
            System.out.println("请求的报文体：" + requestStr);
            //把大的字符串按照&分割，分成a=b的形式
            String[] strs = requestStr.split("&");
            System.out.println("是多少：" + strs[0].toString());
            if (requestStr == strs[0].toString()) {
                System.out.println("結束吧！");
                return "";
            } else {
                String mc_gross = strs[0].toString();
                System.out.println("金额：" + mc_gross);
                //再把a=b的形式取出=后面的值
                String[] str = mc_gross.split("=");
                String amount = str[1].toString();
                System.out.println("真正金额：" + amount);

                String invoice = strs[1].toString();
                System.out.println("订单：" + invoice);
                //再把a=b的形式取出=后面的值
                String[] st = invoice.split("=");
                String orderNumber = st[1].toString();
                System.out.println("真正的订单号：" + orderNumber);

                String payment_status = strs[7].toString();
                System.out.println("" + payment_status);
                String[] payment = payment_status.split("=");
                String paymentStatus = payment[1].toString();
                System.out.println("真正的status：" + paymentStatus);

                String txn_id = strs[23].toString();
                System.out.println("应该是paypal的订单号：" + txn_id);
                String[] tx = txn_id.split("=");
                String txnId = tx[1].toString();
                System.out.println("paypal回传的真正的订单号：" + txnId);

                String mc_currency = strs[32].toString();
                System.out.println("付款货币：" + mc_currency);
                String[] currency = mc_currency.split("=");
                String mcCurrency = currency[1].toString();
                System.out.println("真正付款的货币：" + mcCurrency);

                String protection_eligibility = strs[2].toString();
                System.out.println(protection_eligibility);

                String address_status = strs[3].toString();
                System.out.println(" " + address_status);
                String payer_id = strs[4].toString();
                System.out.println("" + payer_id);
                String address_street = strs[5].toString();
                System.out.println("" + address_street);

                String payment_date = java.net.URLDecoder.decode(strs[6].toString(), "utf-8");
                System.out.println(" " + payment_date);

                String charset = strs[8].toString();
                System.out.println("" + charset);

                String address_zip = strs[9].toString();
                System.out.println(" " + address_zip);
                String first_name = strs[10].toString();
                System.out.println("" + first_name);
                String mc_fee = strs[11].toString();
                System.out.println("" + mc_fee);

                String address_country_code = strs[12].toString();
                System.out.println(" " + address_country_code);
                String address_name = strs[13].toString();
                System.out.println("" + address_name);
                String notify_version = strs[14].toString();
                System.out.println("" + notify_version);

                String custom = strs[15].toString();
                System.out.println(" " + custom);
                String payer_status = strs[16].toString();
                System.out.println("" + payer_status);
                String business = strs[17].toString();
                System.out.println("" + business);

                String address_country = strs[18].toString();
                System.out.println(" " + address_country);
                String address_city = strs[19].toString();
                System.out.println("" + address_city);
                String quantity = strs[20].toString();
                System.out.println("" + quantity);

                String verify_sign = strs[21].toString();
                System.out.println(" " + verify_sign);
                String payer_email = strs[22].toString();
                System.out.println("" + payer_email);

                String payment_type = strs[24].toString();
                System.out.println(" " + payment_type);
                String last_name = strs[25].toString();
                System.out.println("" + last_name);
                String address_state = strs[26].toString();
                System.out.println("" + address_state);

                String receiver_email = strs[27].toString();
                System.out.println(" " + receiver_email);
                String payment_fee = strs[28].toString();
                System.out.println("" + payment_fee);
                String receiver_id = strs[29].toString();
                System.out.println("" + receiver_id);


                String txn_type = strs[30].toString();
                System.out.println(" " + txn_type);
                String item_name = strs[31].toString();
                System.out.println("" + item_name);


                String item_number = strs[33].toString();
                System.out.println(" " + item_number);
                String residence_country = strs[34].toString();
                System.out.println("" + residence_country);
                String receipt_id = strs[35].toString();
                System.out.println("" + receipt_id);
                String[] currencys = receipt_id.split("=");
                String curr = currencys[1].toString();
                System.out.println("真正付款的货币：" + curr);


                String transaction_subject = strs[36].toString();
                System.out.println(" " + transaction_subject);
                String payment_gross = strs[37].toString();
                System.out.println("" + payment_gross);
                String ipn_track_id = strs[38].toString();
                System.out.println("" + ipn_track_id);
                //将paypal回传的交易记录入库保存下来:notification_payment_results_paypal_t
                int c = notificationpaymentService.findCountByOrderNumber(orderNumber);
                if (c <= 0) {
                    //入库
                    PaypalNotificationpaymentResults results = new PaypalNotificationpaymentResults();
                    results.setMc_gross(mc_gross);
                    results.setAmount(amount);
                    results.setOrderNumber(orderNumber);
                    results.setInvoice(invoice);
                    results.setPayment_status(payment_status);
                    results.setPaymentStatus(paymentStatus);
                    results.setMc_currency(mc_currency);
                    results.setMcCurrency(mcCurrency);
                    results.setTxn_id(txn_id);
                    results.setTxnId(txnId);
                    results.setProtection_eligibility(protection_eligibility);
                    results.setAddress_status(address_status);
                    results.setPayer_id(payer_id);
                    results.setAddress_street(address_street);
                    results.setPayment_date(payment_date);
                    results.setCharset(charset);
                    results.setAddress_zip(address_zip);
                    results.setFirst_name(first_name);
                    results.setMc_fee(mc_fee);
                    results.setAddress_country_code(address_country_code);
                    results.setAddress_name(address_name);
                    results.setNotify_version(notify_version);
                    results.setCustom(custom);
                    results.setPayer_status(payer_status);
                    results.setBusiness(business);
                    results.setAddress_country(address_country);
                    results.setAddress_city(address_city);
                    results.setQuantity(quantity);
                    results.setVerify_sign(verify_sign);
                    results.setPayer_email(payer_email);
                    results.setPayment_type(payment_type);
                    results.setLast_name(last_name);
                    results.setAddress_state(address_state);
                    results.setReceiver_email(receiver_email);
                    results.setPayment_fee(payment_fee);
                    results.setReceipt_id(receiver_id);
                    results.setTxn_type(txn_type);
                    results.setItem_name(item_name);
                    results.setItem_number(item_number);
                    results.setResidence_country(residence_country);
                    results.setReceipt_id(receipt_id);
                    results.setTransaction_subject(transaction_subject);
                    results.setPayment_gross(payment_gross);
                    results.setIpn_track_id(ipn_track_id);
                    notificationpaymentService.insertPaymentResultsPaypal(results);
                    System.out.println("payapal回调信息入库完成！");
                }
                //回调的订单是成功的才要入库啊操作
                if ("Completed".equalsIgnoreCase(paymentStatus)) {
                    //查询数据库中当前这条数据插入过没有
                    int count = orderPaymentManagerService.findOrderIdByNotify(orderNumber);
                    if (count <= 0) {//说明当前没有插入记录 ，现在就去插入
                        //支付方式：1-公众号支付，2-paypal，3-oceanpay，4-H5微信支付
                        // 成功就将PayRst设为1；不插入就数据库默认0
                        // 成功就要通知，数据库就记1，不成功就不通知数据库会默认0
                        OrderPaymentManager paymentOrder = new OrderPaymentManager();
                        paymentOrder.setPayRst("success");
                        paymentOrder.setIsNotify("1");
                        paymentOrder.setPayType(payType);
                        paymentOrder.setOrderId(orderNumber);
                        orderPaymentManagerService.updatePayRst(paymentOrder);
                        System.out.println("paypal支付结果入库完成！");

                        //兼容之前的记录：
                        UserboundPaymentOrder order = new UserboundPaymentOrder();
                        order.setPaymentOrderId(orderNumber);
                        order.setPayType("2");
                        order.setIsNotify("1");
                        order.setAmount(amount);
                        order.setOrderCurrency(curr);
                        order.setPayRst("success");
                        orderPaymentManagerService.UpdatePaypalNotify(order);
                        System.out.println("数据入库完成!");

                        //拿到orderId就去做支付结果通知就好
                        return "forward:/payNotify?orderId=" + orderNumber + "&payType=" + Constant.PAY_PAYPAL + "&payAmount=" + amount + "";
                    }
                } else {
                    //订单状态不是完成的状态
                    System.out.println("payment_status是多少:" + payment_status);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    @RequestMapping(value = "/notifyCallback")
    @CrossOrigin
    public String paypalNotifyCallback(HttpServletRequest request, HttpServletResponse response,@RequestBody JsonRootBean jsonRootBean) throws Exception {
        String requestStr = JSON.toJSONString(jsonRootBean);
        if (requestStr == null) {
            System.out.println("请求报文不合法:requestStr为空");
            //在这边处理不是webhook回复
        } else {
            System.out.println("前端请求报文是：" + requestStr);
            jsonRootBean = JSONArray.parseObject(requestStr, JsonRootBean.class);
            Resource resource = jsonRootBean.getResource();
            if (resource == null) {
                System.out.println("resource字节为空！");
            } else {
                //Resource
                String id = resource.getId();
                String state = resource.getState();
                Amount amount = resource.getAmount();
                String payment_mode = resource.getPayment_mode();
                String protection_eligibility = resource.getProtection_eligibility();
                String protection_eligibility_type = resource.getProtection_eligibility_type();
                Transaction_fee transaction_fee = resource.getTransaction_fee();
                String invoice_number = resource.getInvoice_number();
                String parent_payment = resource.getParent_payment();
                //Amount
                String total = amount.getTotal();
                String currency = amount.getCurrency();
                //Details
                Details details = amount.getDetails();
                String subtotal = details.getSubtotal();
                //Transaction_fee
                String value = transaction_fee.getValue();
                String currency1 = transaction_fee.getCurrency();

                int c = notificationpaymentService.findCountByInvoiceNumber(invoice_number);
                if (c <= 0) {
                    PaypalpaymentResults results =new PaypalpaymentResults();
                    results.setPaypal_id(id);
                    results.setState(state);
                    results.setInvoice_number(invoice_number);
                    results.setPayment_mode(payment_mode);
                    results.setProtection_eligibility(protection_eligibility);
                    results.setProtection_eligibility_type(protection_eligibility_type);
                    results.setParent_payment(parent_payment);
                    results.setTotal(total);
                    results.setCurrency(currency);
                    results.setSubtotal(subtotal);
                    results.setTransaction_fee(value);
                    results.setTransaction_fee_currency(currency1);
                    notificationpaymentService.addPaypalpaymentResults(results);
                    System.out.println("payapal-webhook-的回调信息入库完成！");
                }
                //回调的订单是成功的才要入库啊操作
                if ("Completed".equalsIgnoreCase(state)) {
                    //查询数据库中当前这条数据插入过没有
                    int count = orderPaymentManagerService.findOrderIdByNotify(invoice_number);
                    if (count <= 0) {//说明当前没有插入记录 ，现在就去插入
                        //支付方式：1-公众号支付，2-paypal，3-oceanpay，4-H5微信支付
                        // 成功就将PayRst设为1；不插入就数据库默认0
                        // 成功就要通知，数据库就记1，不成功就不通知数据库会默认0
                        OrderPaymentManager paymentOrder = new OrderPaymentManager();
                        paymentOrder.setPayRst("success");
                        paymentOrder.setIsNotify("1");
                        paymentOrder.setPayType(payType);
                        paymentOrder.setOrderId(invoice_number);
                        orderPaymentManagerService.updatePayRst(paymentOrder);
                        System.out.println("paypal支付结果入库完成！");

                        //兼容之前的记录：
                        UserboundPaymentOrder order = new UserboundPaymentOrder();
                        order.setPaymentOrderId(invoice_number);
                        order.setPayType("2");
                        order.setIsNotify("1");
                        order.setAmount(total);
                        order.setOrderCurrency(currency);
                        order.setPayRst("success");
                        orderPaymentManagerService.UpdatePaypalNotify(order);
                        System.out.println("数据入库完成!");

                        //拿到orderId就去做支付结果通知就好
                        return "forward:/payNotify?orderId=" + invoice_number + "&payType=" + Constant.PAY_PAYPAL + "&payAmount=" + amount + "";
                    }else{
                        //已经收到了
                        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                        out.write("SUCCESS".getBytes());
                        out.flush();
                        out.close();
                    }
                } else {
                    //订单状态不是完成的状态
                    System.out.println("状态是多少:" + state);
                }

            }

        }
        return null;
    }
}
